package cn.lger.service;

import cn.lger.dao.ArticleDao;
import cn.lger.pojo.Article;
import cn.lger.pojo.Page;
import cn.lger.util.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * Code that Changed the World
 *
 * @author Pro
 * @date 2018-06-14.
 */
@Service
public class ArticleService {

    @Resource
    private ArticleDao articleDao;

    public Article findOneById(int id) {
        return articleDao.findOneById(id);
    }

    public Article findOneByArticleIdAndUserId(int articleId, int userId) {
        return articleDao.findOneByArticleIdAndUserId(userId, articleId);
    }

    public Page<Article> findOnePage(Integer currentPage, Integer size, Integer categoryId, Integer userId) {
        Page<Article> page = PageUtil.generator(currentPage, size);
        page.setCount(articleDao.getTotal(userId, categoryId));
        List<Article> list = articleDao.findByCondition(userId, categoryId, page.getPage(), page.getSize());
        page.setContent(list);
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    public int insertOne(Article article) {
        return articleDao.insertOne(article);
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateByUserId(Article article, int userId) {
        if (articleDao.findOneByArticleIdAndUserId(userId, article.getId()) != null){
            return articleDao.updateOne(article);
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int deleteByUserIdAndArticleId(int id, int userId) {
        if (articleDao.findOneByArticleIdAndUserId(userId, id) != null){
            return articleDao.deleteOneById(id);
        }
        return 0;
    }

    @Transactional(rollbackFor = Exception.class)
    public int deleteOneById(int id) {
        return articleDao.deleteOneById(id);
    }
}
